import React, { Component } from "react";
import { Table, Button, Form, Modal, Input, Popconfirm ,message} from "antd";
// 引入编辑器组件
import BraftEditor from "braft-editor";
// 引入编辑器样式
import "braft-editor/dist/index.css";
import "../article/ArticleList.less";
import UploadImg from "../../component/uploadImg";
import {
  querylanmuList,
  addlanmu,
  deletelanmu,
  updatelanmu,
  batchdeletelanmu,
} from "../../api/lanmuList";
import { QuestionCircleOutlined } from "@ant-design/icons";
export default class LanmuList extends Component {
  constructor(props) {
    super();
    this.state = {
      editorState: BraftEditor.createEditorState(null), //富本文编辑
      editorState1: BraftEditor.createEditorState(null),
      selectArr: [],
      isshow: false,
      newLanmu: {
        lanmuName: "",
        scribe: "",
        img: "",
      },
      updateLanmu: {
        _id: "",
        lanmuName: "",
        scribe: "",
        img: "",
      },
      visible: false,
      visible1: false,
      columns: [
        {
          key: "Id",
          title: "Id",
          render: (text, record, index) => {
            return <>{index + 1}</>;
          },
        },
        {
          key: "lanmuName",
          title: "栏目名称",
          dataIndex: "lanmuName",
        },
        {
          key: "scribe",
          title: "描述",
          dataIndex: "scribe",
          render: (item) => <p dangerouslySetInnerHTML={{ __html: item }} />,
        },
        {
          key: "img",
          title: "栏目缩略图",
          dataIndex: "img",
          render: (img) => <img style={{ width: "100px" }} src={img} alt="" />,
        },
        {
          key: "handle",
          title: "操作",
          render: (text, record, index) => {
            // console.log(text,record,index)
            return (
              <>
                <Button type="primary" onClick={() => this.editItem(record)}>
                  编辑
                </Button>

                <Popconfirm
                  title="亲，你确定要删除吗?"
                  onConfirm={() => this.deleteItem(record)}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="primary" danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            );
          },
        },
      ],
      data: [],
    };
  }

  // 获取数据
  getLanmuList() {
    querylanmuList().then((res) => {
      let arr = res.data;
      arr.forEach((item) => {
        item.key = item._id;
      });
      this.setState({
        data: [...arr],
      });
    });
  }

  componentDidMount() {
    this.getLanmuList();
  }
  //显示编辑弹窗
  editItem(record) {
    console.log(record);
    this.setState({
      visible1: true,
      // 使用BraftEditor.createEditorState将html字符串转换为编辑器需要的editorStat
      editorState1: BraftEditor.createEditorState(record.scribe),
      updateLanmu: {
        ...this.state.updateLanmu,
        _id: record._id,
        lanmuName: record.lanmuName,
        scribe: record.scribe,
        img: record.img,
      },
    });
  }
  //显示增加弹窗
  addList() {
    this.setState({
      editorState: BraftEditor.createEditorState(null),
      newLanmu: {
        ...this.state.newLanmu,
        lanmuName: "",
        scribe: "",
        img: "",
      },
      isshow: false,
      visible: true,
    });
  }
  //增加栏目
  handleOk = () => {
    this.setState(
      {
        newLanmu: {
          ...this.state.newLanmu,
          scribe: this.state.editorState.toHTML(),
        },
      },
      () => {
        addlanmu(this.state.newLanmu).then((res) => {
          console.log(res);
          if (res.state === "添加成功") {
            this.getLanmuList();
            this.setState({
              visible: false,
            });
          }
        });
      }
    );
  };
  //修改栏目
  handleOk1 = () => {
    console.log("handleOk1");
    this.setState(
      {
        updateLanmu: {
          ...this.state.updateLanmu,
          scribe: this.state.editorState1.toHTML(),
        },
      },
      () => {
        updatelanmu(this.state.updateLanmu).then((res) => {
          if (res.state === "修改成功") {
            this.getLanmuList();
            this.setState({
              visible1: false,
            });
          }
        });
      }
    );
  };
  //取消修改
  handleCancel1 = () => {
    this.setState({
      visible1: false,
    });
  };
  //取消增加
  handleCancel = () => {
    this.setState({
      visible: false,
    });
  };
  //删除栏目
  deleteItem(record) {
    console.log(record);
    deletelanmu({ _id: record._id }).then((res) => {
      if (res.state === "删除成功") {
        this.getLanmuList();
      }
    });
  }
  // 父组件利用props传递方法给子组件，子组件回调这个方法的同时，
  // 将数据传递进去，使得父组件的相关方法得到回调，
  // 这个时候就可以把数据从子组件传递给父组件了
  //获取图片地址 父
  getImgUrl = (imgUrl, isshow) => {
    console.log(imgUrl);
    this.setState({
      isshow: isshow,
      newLanmu: {
        ...this.state.newLanmu,
        img: imgUrl,
      },
    });
  };
  //双向绑定
  changeVal(e, key) {
    this.setState({
      newLanmu: {
        ...this.state.newLanmu,
        [key]: e.target.value,
      },
    });
  }
  //双向绑定
  changeVal1(e, key) {
    this.setState({
      updateLanmu: {
        ...this.state.updateLanmu,
        [key]: e.target.value,
      },
    });
  }
  // 批量删除文章弹窗
  showModalDe = () => {
    console.log(this.state.selectArr, "批量删除选中项，弹窗显示");
    if (this.state.selectArr.length >= 1) {
      this.setState({
        visibleDe: true,
      });
    } else {
      message.warning({
        content: "请先勾选删除项",
        style: {
          marginTop: "5%",
        },
      });
      this.setState({
        visibleDe: false,
      });
    }
  };
  // 批量删除保存
  handleOkDe = (e) => {
    console.log("selected", this.state.selectArr);
    batchdeletelanmu({ strArr: JSON.stringify(this.state.selectArr) }).then(
      (res) => {
        if (res.state === "删除成功") {
          this.getLanmuList();
          this.setState({
            visibleDe: false,
          });
        }
      }
    );
  };
  // 批量删除取消
  handleCancelDe = (e) => {
    // console.log(e);
    this.setState({
      visibleDe: false,
    });
  };

  //富文本编辑
  handleEditorChange = (editorState) => {
    this.setState({ editorState });
  };
  handleEditorChange1 = (editorState1) => {
    this.setState({ editorState1 });
  };
  // submitContent = () => {
  //   // 在编辑器获得焦点时按下ctrl+s会执行此方法
  //   // 编辑器内容提交到服务端之前，可直接调用editorState.toHTML()来获取HTML格式的内容
  //   const htmlContent = this.state.editorState.toHTML();
  //   console.log(htmlContent);
  // };
  render() {
    return (
      <div>
        <div
          style={{
            backgroundColor: "#f2f2f2",
            width: "100%",
            clor: "#fff",
            height: "50px",
            display: "flex",
            alignItems: "center",
            marginBottom: "10px",
          }}
        >
          <Button
            style={{
              backgroundColor: "#fe6737",
              margin: " 0 10px",
              color: "#fff",
            }}
            type="default"
            // onClick={() => this.deleteBatch()}
            onClick={() => this.showModalDe()}
          >
            批量删除
          </Button>
          <Modal
            title="提示信息"
            visible={this.state.visibleDe}
            onOk={this.handleOkDe}
            onCancel={this.handleCancelDe}
            cancelText="取消"
            okText="确定"
            centered
          >
            <Form
              labelCol={{ span: 5 }}
              wrapperCol={{ span: 14 }}
              layout="inline"
            >
              <QuestionCircleOutlined
                style={{ fontSize: "26px", color: "#F4C706" }}
              />
              <p style={{ lineHeight: "26px", marginLeft: "8px" }}>
                确定要删除吗？
              </p>
            </Form>
          </Modal>
          <Button onClick={() => this.addList()} type="primary">
            增添栏目
          </Button>
        </div>
        <Table
          pagination={{
            defaultPageSize: 5,
          }}
          rowSelection={{
            type: "checkbox",
            onChange: (selectedRowKeys, selectedRows) => {
              console.log("selectedRows: ", selectedRows);
              let arr = selectedRows.map((item) => {
                return { _id: item._id };
              });
              console.log(arr, "arr");
              this.setState({
                selectArr: arr,
              });
            },
          }}
          columns={this.state.columns}
          dataSource={this.state.data}
        />

        <Modal
          title="添加栏目"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
          width={1000}
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 14 }}
            layout="horizontal"
          >
            <Form.Item label="栏目名称" required="true">
              <Input
                type="text"
                value={this.state.newLanmu.lanmuName}
                onChange={(e) => this.changeVal(e, "lanmuName")}
              />
            </Form.Item>
            <Form.Item label="栏目缩略图" required="true">
              <UploadImg
                isshow={this.state.isshow}
                getImgUrl={this.getImgUrl}
              />
            </Form.Item>
            <Form.Item label="描述" className="my-component edit">
              <BraftEditor
                value={this.state.editorState}
                onChange={this.handleEditorChange}
                style={{ border: "1px solid #d9d9d9" }}
              />
            </Form.Item>
          </Form>
        </Modal>

        <Modal
          title="修改栏目"
          visible={this.state.visible1}
          onOk={this.handleOk1}
          onCancel={this.handleCancel1}
          okText="保存"
          cancelText="取消"
          width={1000}
        >
          <Form
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 14 }}
            layout="horizontal"
          >
            <Form.Item label="栏目名称" required="true">
              <Input
                type="text"
                value={this.state.updateLanmu.lanmuName}
                onChange={(e) => this.changeVal1(e, "lanmuName")}
              />
            </Form.Item>
            <Form.Item label="栏目缩略图" required="true">
              <img src={this.state.updateLanmu.img} alt="" />
            </Form.Item>
            <Form.Item label="描述" className="my-component edit">
              <BraftEditor
                value={this.state.editorState1}
                onChange={this.handleEditorChange1}
                style={{ border: "1px solid #d9d9d9" }}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
